package com.lebang.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.domain.CencesBusMember;
import com.lebang.domain.CencesSdkErrorLog;
import com.lebang.domain.EmailSdkerrorSendRecord;
import com.lebang.feign.CencesHundredPointFeign;
import com.lebang.feign.HundredAwardsFeign;
import com.lebang.feign.bus.CencesApiCountFeign;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.model.RequestUserInfo;
import com.lebang.model.cences.DoubleConfig;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.AppAdControService;
import com.lebang.service.EmailSdkerrorSendRecordService;
import com.lebang.service.cences.*;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.lebang.service.buss.MemberTradeService.CATEGORY_KEY;
import static com.lebang.service.sys.AdErrorConfigService.ERROR_SDK_KEY;

/**
 * @Author: hwq
 * @Date: 2019/10/9 15:46
 * @Version 1.0
 */
@Slf4j
@Component
public class CencusTask {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private RedisSdkClient redisSdkClient;
    @Autowired
    private CensusService censusService;
    @Autowired
    private CencesEarnDayService cencesEarnDayService;
    @Autowired
    private CencesMasterService cencesMasterService;
    @Autowired
    private CencesOutlayService cencesOutlayService;
    @Autowired
    private CencesClickService cencesClickService;
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private CencesNewHandService cencesNewHandService;
    @Autowired
    private CencesDownloadMemberService cencesDownloadMemberService;
    @Autowired
    private CencesNewsJokeService cencesNewsJokeService;
    @Autowired
    private CencesBrandEffectService cencesBrandEffectService;
    @Autowired
    private CencesBrandActiveService cencesBrandActiveService;
    @Autowired
    private CencesCommonSdkService cencesCommonSdkService;
    @Autowired
    private AppAdControService appAdControService;
    @Autowired
    private CencesBrandRegisterService cencesBrandRegisterService;
    @Autowired
    private CencesObsService cencesObsService;
    @Autowired
    private CencesInviteService cencesInviteService;
    @Autowired
    private CencesEarnDataService cencesEarnDataService;
    @Autowired
    private CencesRouseClickService cencesRouseClickService;
    @Autowired
    private CencesBusMemberService cencesBusMemberService;
    @Autowired
    private CencesApiCountFeign cencesApiCountFeign;
    @Autowired
    private CencesHundredDownloadRecordService cencesHundredDownloadRecordService;
    @Autowired
    private HundredAwardsFeign hundredAwardsFeign;
    @Autowired
    private CencesHundredPointFeign cencesHundredPointFeign;
    @Autowired
    private CencesHundredPointService cencesHundredPointService;
    @Autowired
    private CencesSdkErrorLogService cencesSdkErrorLogService;
    @Autowired
    private EmailSdkerrorSendRecordService emailSdkerrorSendRecordService;
    @Autowired
    private CencesCoreDataService cencesCoreDataService;

    @Value("${info.is-cences}")
    private Boolean isStar;
    @Value("${info.appId}")
    private Integer appId;

    /**
     * 每日3点统计数据并且记录表格
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void execute() {
        if (!isStar) {
            return;
        }
        String time = LocalDate.now().minusDays(3).format(DateTimeFormatter.ISO_DATE);
        String time5 = LocalDate.now().minusDays(5).format(DateTimeFormatter.ISO_DATE);


        if (redisClient.tryGetDistributedLock("lock:Scheduled:census", UUIDUtil.M(), 100000)) {
            for (TaskCategory e : TaskCategory.values()) {
                redisClient.delOne(CATEGORY_KEY + e.name() + ":" + time);
                redisClient.delOne(CATEGORY_KEY + e.name() + ":" + time5);
            }
            redisClient.delOne(CATEGORY_KEY + "ALL:" + time5);
            List<String> brand = lbbMemberMapper.selectBrand();
            log.info("开始统计数据...");
            LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
            censusService.newCensus(dateTime);
            censusService.dayCensus(dateTime);
            censusService.emailData(dateTime);
            cencesEarnDayService.starDataInit(dateTime, brand);
            cencesMasterService.starDataInit(dateTime, brand);
            cencesOutlayService.starDataInit(dateTime, brand);
            cencesClickService.starDataInit(dateTime, brand);
            cencesNewHandService.starDataInit(dateTime, brand);
            cencesDownloadMemberService.starDataInit(dateTime, brand);
            cencesNewsJokeService.starDataInit(dateTime, brand);
            cencesBrandEffectService.starDataInit(dateTime, brand);
            cencesBrandActiveService.starDataInit(dateTime, brand);
            cencesCommonSdkService.starDataInit(dateTime, brand);
            appAdControService.addData(dateTime.minusDays(1));
            cencesBrandRegisterService.starDataInit(dateTime);
            cencesObsService.starDataInit(dateTime);
            cencesInviteService.starDataInit(dateTime);

            cencesEarnDataService.starDataInit(dateTime);
            cencesRouseClickService.starDataInit(dateTime);

            if (appId == 8) {
                //公交百倍金币统计
                List<CencesBusMember> activeMemberList = cencesHundredPointService.activeMemberList(dateTime);
                RequestUserInfo userInfo = new RequestUserInfo();
                userInfo.setAppId(appId);
                cencesHundredPointFeign.starDataInit(userInfo, dateTime, JSONObject.toJSONString(activeMemberList), JSONObject.toJSONString(brand));
                //公交用户统计
                cencesBusMemberService.starDataInit(dateTime);
                //公交接口统计
                cencesApiCountFeign.starDataInit(dateTime, JSONObject.toJSONString(brand));
                //公交每日必赚统计
                JsonData data = hundredAwardsFeign.doubleConfig(userInfo);
                List<DoubleConfig> configList = JSONArray.parseArray(JSONObject.toJSONString(data.getData()), DoubleConfig.class);
                cencesHundredDownloadRecordService.starDataInit(dateTime, configList);
            }
            //信息上报统计
            cencesSdkErrorLogService.starDataInit(dateTime);
            cencesCoreDataService.starDataInit(dateTime);
        }else {
            //其他系统执行
            log.info("其他系统执行");
        }
        log.info("统计完成...");
    }

    /**
     *  每小时检查是否有错误码数量超过最大值,超过发送邮件
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void sendEmail() {
        if (!isStar) {
            return;
        }
        if (redisSdkClient.tryGetDistributedLock("lock:Scheduled:sendSuscesEmail", UUIDUtil.M(), 100000)) {
            LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
            int time = Integer.parseInt(dateTime.toLocalDate().format(df));
            String nowDateString = LocalDate.now().format(DateTimeFormatter.ISO_DATE);
            Map<String, String> hGetAll = redisClient.hgetall(ERROR_SDK_KEY+nowDateString);
            List<EmailSdkerrorSendRecord> records=new ArrayList<>();
            for (Map.Entry<String, String> entry : hGetAll.entrySet()) {
                int count = Integer.parseInt(entry.getValue());
                if (count > 2000){
                    String[] split = entry.getKey().split(":");
                    EmailSdkerrorSendRecord record = new EmailSdkerrorSendRecord();
                    record.setCreateTime(LocalDateTime.now());
                    record.setTime(time);
                    record.setSdkKey(split[0]);
                    record.setErrorCode(split[1]);
                    record.setErrorCount(count);
                    record.setErrorMessage(redisClient.get(split[0]+":"+split[1]));
                    records.add(record);
                }
            }
            //过滤今天已经发送的sdk_error
            List<EmailSdkerrorSendRecord> list=emailSdkerrorSendRecordService.selectByTime(dateTime,LocalDateTime.now());
            records.removeAll(list);
            if (records.size() != 0){
                //发邮件
                cencesSdkErrorLogService.sendEmail(records,dateTime);
            }

        } else {
            //其他系统执行
            log.info("其他系统执行");
        }
    }

//    /**
//     * 发送邮件
//     */
//    @Scheduled(cron = "0 0 4 * * ?")
//    public void sendEmail() {
//
//        if(!isStar){
//            return;
//        }
//        if(redisSdkClient.tryGetDistributedLock("lock:Scheduled:sendSuscesEmail", UUIDUtil.M(),100000)) {
//            LocalDateTime dateTime=LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
//            censusService.sendEmail(dateTime);
//        }else {
//            //其他系统执行
//            log.info("其他系统执行");
//        }
//    }

}
